package com.tarena.lbs.business.servcie.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.constant.BusinessTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.BusinessService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.utils.PageConverter;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.tarena.lbs.business.enums.BusinessResultEnum.*;

@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private StoreRepository storeRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;
    @Override
    public PageResult<BusinessVO> pageList(BusinessQuery query) throws BusinessException {
        log.debug("查询商家列表:{}",query);
        // 获取当前登录用户信息
        UserPrinciple userPrinciple= AuthenticationContextUtils.getUserPrinciple();
        // 获取用户角色
        Roles role = userPrinciple.getRole();
        // 非管理员用户不允许查看商家列表
        if (role==Roles.SHOP){
            Integer adminId = userPrinciple.getId();
            log.debug("管理员用户:{}",adminId);
            AdminDto adminDto = userApi.getAdminById(adminId);
            Asserts.isTrue(adminDto == null, new BusinessException(BUSINESS_NOT_EXISTS));
            query.setBusinessId(adminDto.getBusinessId());
        }
        // 查询业务数据并转换为业务对象列表
        PageInfo<BusinessPO> pageInfo = businessRepository.pageList(query);
        List<BusinessPO> businessPOS = pageInfo.getList();
        List<BusinessVO> businessVOS = new ArrayList<>();
        // 如果查询结果不为空，则将业务对象转换为业务视图对象
        if (CollectionUtils.isNotEmpty(businessPOS)){
           businessVOS=businessPOS.stream().map(businessPO -> {
               BusinessVO businessVO = new BusinessVO();
               BeanUtils.copyProperties(businessPO,businessVO);
               return businessVO;
           }).collect(Collectors.toList());
        }
        return PageConverter.convert(pageInfo,businessVOS);
    }

    @Override
    public void save(BusinessParam param) throws BusinessException {
        log.debug("新增商家:{}",param);
        // 获取当前登录用户的信息
        UserPrinciple userPrinciple= AuthenticationContextUtils.getUserPrinciple();
        // 获取用户的角色
        Roles role = userPrinciple.getRole();
        // 检查用户是否有管理员权限
        if (role!=Roles.ADMIN){
            throw new BusinessException(AUTH_NOT_EXISTS);
        }
        // 创建一个新的商家实体对象
        BusinessPO businessPO = new BusinessPO();
        // 获取商家名称
        String businessName= param.getBusinessName();
        // 检查商家名称是否已存在
        Long count = businessRepository.countByBusinessName(businessName);
        Asserts.isTrue(count>0,new BusinessException(BUSINESS_EXISTS));
        // 将请求参数复制到商家实体对象中
        BeanUtils.copyProperties(param,businessPO);
        // 设置商家的录入时间
        businessPO.setEntryTime(new Date());
        // 插入商家信息到数据库
        businessRepository.insert(businessPO);
        // 获取新插入商家的ID
        Integer businessId=businessPO.getId();
        // 绑定商家图片
        bindPictures(businessId,param);
    }

    private void bindPictures(Integer businessId, BusinessParam param) throws BusinessException {
        // 创建一个列表，用于存储图片更新参数对象
        List<PicUpdateParam> picUpdateParamList = new ArrayList<>();
        // 创建一个图片更新参数对象，用于商家营业执照的更新
        PicUpdateParam licenseParam = new PicUpdateParam();
        // 设置营业执照的业务类型
        licenseParam.setBusinessType(BusinessTypes.BIZ_LICENSE);
        // 设置业务ID
        licenseParam.setBusinessId(businessId);
        // 获取营业执照的URL
        String licenseUrl = param.getBusinessLicense();
        // 设置文件UUID
        licenseParam.setFileUuid(getUuid(licenseUrl));
        // 创建一个图片更新参数对象，用于商家标志的更新
        PicUpdateParam LogoParam = new PicUpdateParam();
        // 设置商家标志的业务类型
        LogoParam.setBusinessType(BusinessTypes.BIZ_LOGO);
        // 设置业务ID
        LogoParam.setBusinessId(businessId);
        // 获取商家标志的URL
        String logoUrl=param.getBusinessLogo();
        // 设置文件UUID
        LogoParam.setFileUuid(getUuid(logoUrl));
        // 将参数对象添加到列表中
        picUpdateParamList.add(licenseParam);
        picUpdateParamList.add(LogoParam);
        // 调用批量更新业务图片的API，并获取结果
        Boolean result =attachApi.bathUpdateBusiness(picUpdateParamList);
        // 断言更新结果，如果不成功，则抛出业务异常
        Asserts.isTrue(!result,new BusinessException(BINDING_FAILURE));
    }
    private String getUuid (String url){
        return url.split("/")[4];
    }

    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) throws BusinessException {
        log.debug("商家详情:{}",businessId);
        AuthenticationContextUtils.getUserPrinciple();
        BusinessPO businessPO = businessRepository.busiStoreDetail(businessId);
        BusinessStoreVO businessStoreVO = new BusinessStoreVO();
        if (businessPO!=null){
            BeanUtils.copyProperties(businessPO,businessStoreVO);
        }
        log.debug("商家旗下店铺详情");
        List<StorePO> storePOS = storeRepository.selectStoreById(businessId);
        List<StoreVO> storeVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(storePOS)){
            storeVOS=storePOS.stream().map(storePO -> {
                StoreVO storeVO = new StoreVO();
                BeanUtils.copyProperties(storePO,storeVO);
                return storeVO;
            }).collect(Collectors.toList());
        }
        businessStoreVO.setStoreVOList(storeVOS);
        return businessStoreVO;
    }

    @Override
    public void updateStatus(BusinessParam param) {
        log.debug("审批商家:{}",param);
        BusinessPO businessPO = new BusinessPO();
        BeanUtils.copyProperties(param,businessPO);
        businessRepository.update(businessPO);
    }


}
